<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-button
          type="danger"
          icon="delete"
          class="handle-del mr10"
          @click="deleteAllHandler"
          >批量删除</el-button
        >
        <el-input
          placeholder="请输入关键字"
          class="handle-input mr10"
          v-model="searchInfo"
        ></el-input>
        <el-button type="primary" icon="search" @click="searchGoods"
          >搜索</el-button
        >
        <el-button type="primary" @click="addGoodsVisible = true"
          >添加商品</el-button
        >
        <el-button type="primary" @click="handlerDownloadALL"
          >导出全部</el-button
        >
      </div>
      <el-table
        border
        class="table"
        :data="goods.slice((currentPage - 1) * 10, currentPage * 10)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="goods_id"
          label="序号"
          sortable
          width="150"
        ></el-table-column>
        <el-table-column
          prop="goods_name"
          label="商品名称"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="goods_category"
          label="商品类别"
        ></el-table-column>
        <el-table-column prop="goods_title" label="商品标题"></el-table-column>
        <el-table-column prop="goods_info" label="商品描述"></el-table-column>
        <el-table-column label="商品图片" align="center">
          <template slot-scope="scope">
            <div class="demo-image">
              <div class="block">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="scope.row.goods_img"
                  fit="fill"
                  @click="bigPicHandler(scope.$index, scope.row.goods_img)"
                ></el-image>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品规格" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-view"
              @click="checkMsg(scope.$index, scope.row.goods_standard)"
              >详情</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="goods.length"
          :page-size="pageSize"
          :page-sizes="[3, 5, 10, 20, 50]"
          :current-page="currentPage"
          @current-change="currentChange"
          @size-change="sizeChangeHandler"
        >
        </el-pagination>
      </div>
      <!-- 商品规格详情框 -->
      <el-dialog title="商品详情" :visible.sync="showGoodsVisible" v-dialogDrag>
        <el-form>
          <el-form-item
            label="商品规格"
            :label-width="formLabelWidth"
            v-for="item in this.standardForm"
            :key="item.id"
          >
            <template>
              <span>{{ item.standard_txt }}</span>
              <p>原价：{{ item.standard_oldPrice }}</p>
              <p>现价：{{ item.standard_price }}</p>
            </template>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="showGoodsVisible = false"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <!-- 编辑框 -->
      <el-dialog
        title="修改信息"
        :visible.sync="editGoodsVisible"
        ref="editGoodsForm"
        v-dialogDrag
      >
        <el-form ref="editGoodsForm" :rules="editRule" :model="goodsForm">
          <el-form-item
            label="编号"
            :label-width="formLabelWidth"
            prop="goods_id"
            hidden
          >
            <el-input
              v-model="goodsForm.goods_id"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="商品名"
            :label-width="formLabelWidth"
            prop="goods_name"
          >
            <el-input
              v-model="goodsForm.goods_name"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="商品类别"
            :label-width="formLabelWidth"
            prop="goods_category"
          >
            <el-input
              v-model="goodsForm.goods_category"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="商品标题"
            :label-width="formLabelWidth"
            prop="goods_title"
          >
            <el-input
              v-model="goodsForm.goods_title"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="商品描述"
            :label-width="formLabelWidth"
            prop="goods_info"
          >
            <el-input
              v-model="goodsForm.goods_info"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <!-- 上传图片 -->
          <el-form-item
            label="商品图片"
            :label-width="formLabelWidth"
            prop="goods_img"
          >
            <el-upload
              drag
              accept=".jpg,.gif,.jpeg"
              action="''"
              :before-upload="beforeUpload"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                点击上传图片
                <br />
                <br />
                {{ goodsForm.goods_img }}
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editGoodsVisible = false">取 消</el-button>
          <el-button type="primary" @click.native="editGoodsHanlder"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <!-- 图片预览 -->
      <el-dialog
        :visible.sync="dialogVisible"
        width="40%"
        style="text-align: center"
      >
        <img :src="this.srcList" style="width:300px;height:300px" />
      </el-dialog>
      <!-- 添加 -->
      <el-dialog
        title="添加信息"
        :visible.sync="addGoodsVisible"
        ref="addGoodsForm"
        v-dialogDrag
      >
        <el-form :model="addGoodsForm" ref="addGoodsForm">
          <el-form-item
            label="编号"
            :label-width="formLabelWidth"
            prop="goods_id"
            hidden
          >
            <el-input
              v-model="addGoodsForm.goods_id"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="商品名"
            :label-width="formLabelWidth"
            prop="goods_name"
          >
            <el-input
              v-model="addGoodsForm.goods_name"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="商品价格"
            :label-width="formLabelWidth"
            prop="goods_price"
          >
            <el-input
              v-model="addGoodsForm.goods_price"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="商品类别"
            :label-width="formLabelWidth"
            prop="goods_category"
          >
            <el-input
              v-model="addGoodsForm.goods_category"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="商品标题"
            :label-width="formLabelWidth"
            prop="goods_title"
          >
            <el-input
              v-model="addGoodsForm.goods_title"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="商品副标题"
            :label-width="formLabelWidth"
            prop="goods_info"
          >
            <el-input
              v-model="addGoodsForm.goods_info"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <!-- 上传图片 -->
          <el-form-item
            label="商品图片"
            :label-width="formLabelWidth"
            prop="goods_img"
          >
            <el-upload
              drag
              accept=".jpg,.gif,.jpeg"
              action="''"
              :before-upload="beforeUpload"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                点击上传图片
                <br />
                <br />
                bbb:mp3，ccc
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addGoodsVisible = false">取 消</el-button>
          <el-button type="primary" @click="addGoodsHandler">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  getGoodsList,
  updateGoods,
  addGoods,
  deleteGoods,
  saveFile
} from "../../../api/api";
import Vue from "vue";
import { Image } from "element-ui";
import Xlsx from "xlsx";
Vue.use(Image);
export default {
  data() {
    return {
      goods: [],
      goodsList: [],
      delGoods: [],
      srcList: "",
      pageSize: 3,
      editGoodsVisible: false,
      showGoodsVisible: false,
      dialogVisible: false,
      standardForm: {},
      goodsForm: {},
      searchInfo: "",
      addGoodsForm: {
        goods_name: "",
        goods_title: "",
        goods_info: "",
        goods_img: "",
        goods_price: 0
      },
      formLabelWidth: "120px",
      addGoodsVisible: false,
      // total: 0,
      currentPage: 1,
      editRule: {
        goods_name: [
          {
            required: true,
            message: "请输入商品名",
            trigger: "blur"
          }
        ],
        goods_price: [
          {
            required: true,
            message: "请输入商品价格",
            trigger: "blur"
          }
        ]
      }
    };
  },
  mounted() {
    this.getGoods();
  },
  methods: {
    sizeChangeHandler(size) {
      this.pageSize = size;
    },
    // 导出Excel事件
    handlerDownloadALL() {
      const tableData = [
        ["商品编号", "商品名称", "商品类别", "商品标题", "商品描述", "商品图片"]
      ];
      this.goods.forEach(item => {
        const rowData = [
          item.goods_id,
          item.goods_name,
          item.goods_category,
          item.goods_title,
          item.goods_info,
          item.goods_img
        ];
        tableData.push(rowData);
      });
      const ws = Xlsx.utils.aoa_to_sheet(tableData);
      const wb = Xlsx.utils.book_new();
      const date = new Date();
      Xlsx.utils.book_append_sheet(wb, ws, "商品数据"); // 工作簿名称
      Xlsx.writeFile(wb, `商品数据${date.toLocaleString()}.xlsx`); // 保存的文件名
    },
    bigPicHandler(index, row) {
      this.dialogVisible = true;
      this.srcList = row;
    },
    beforeUpload(file) {
      console.log(file);
      const fileName = file.name;
      if (file.size > 50 * 1024 * 1024) {
        this.$message.warning(`你选择的文件过大！`);
        return false;
      }
      console.log(fileName);
      saveFile(file)
        .then(res => {
          console.log(res);
          this.$message.success(`上传成功！`);
          this.addGoodsForm.goods_img = res[0].img;
          this.goodsForm.goods_img = res[0].img;
          this.srcList = res[0].img;
        })
        .catch(errMsg => {
          this.$message.warning(errMsg.toString());
        });
      return false;
    },
    handleSelectionChange(delGoods) {
      this.delGoods = delGoods;
    },
    getGoods() {
      getGoodsList().then(result => {
        this.goods = result;
      });
      this.goodsList = [...this.goods];
      console.log(this.goodsList);
    },
    checkMsg(index, row) {
      this.showGoodsVisible = true;
      this.standardForm = Object.assign({}, row);
      console.log(this.standardForm);
    },
    currentChange(val) {
      this.currentPage = val;
      this.getGoods();
    },
    searchGoods() {
      if (this.searchInfo.length === 0) {
        this.getGoods();
      }
      if (this.searchInfo) {
        this.goods = this.goods.filter(item => {
          return Object.keys(item).some(key => {
            return String(item[key]).indexOf(this.searchInfo) > -1;
          });
        });
      }
    },
    deleteAllHandler() {
      this.$confirm("确认删除这些商品吗？", "提示", {
        type: "warning"
      })
        .then(() => {
          let delIds = this.delGoods.map(item => item.goods_id);
          for (let i = 0; i < delIds.length; i++) {
            deleteGoods(this.delGoods[i]).then(result => {
              if (result) {
                this.goods = this.goods.filter(item => {
                  if (item.goods_id !== delIds[i]) {
                    return item;
                  }
                });
              }
            });
          }
          this.$message({
            type: "success",
            message: "删除成功！"
          });
        })
        .catch(() => {
          console.log("cancel");
        });
    },
    handleEdit(index, row) {
      this.editGoodsVisible = true;
      this.goodsForm = Object.assign({}, row);
    },
    handleDelete(index, row) {
      this.$confirm("确认删除该商品？", "提示", {
        type: "warning"
      })
        .then(() => {
          deleteGoods(row).then(result => {
            if (result) {
              this.goods = this.goods.filter(item => {
                if (item.goods_id !== row.goods_id) {
                  return item;
                }
              });
              this.$message({
                type: "success",
                message: "删除成功！"
              });
            }
          });
        })
        .catch(() => {
          console.log("取消删除");
        });
    },
    addGoodsHandler() {
      if (!this.addGoodsForm) return;
      let params = Object.assign(
        { goods_id: this.goods.length + 1 },
        this.addGoodsForm
      );
      addGoods(params).then(result => {
        if (result) {
          this.$message({
            type: "success",
            message: "添加成功！"
          });
          this.goods = [params, ...this.goods];
          this.addGoodsVisible = false;
        }
      });
    },
    editGoodsHanlder() {
      this.$refs["editGoodsForm"].validate(valid => {
        if (valid) {
          let data = this.goodsForm;
          console.log(data);
          updateGoods(data)
            .then(result => {
              if (result) {
                this.$message({
                  type: "success",
                  message: "修改成功！"
                });
                this.goods = this.goods.map(item => {
                  if (item.goods_id === data.goods_id) {
                    return {
                      ...item,
                      ...data
                    };
                  }
                  return item;
                });
                this.editGoodsVisible = false;
                this.goodsForm = {};
              }
            })
            .catch(e => console.log(e));
        }
      });
    }
  }
};
</script>
<style>
.el-image__inner {
  width: 100px;
}
</style>
<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
</style>
